const { DataTypes } = require('sequelize')

module.exports = (sequelize) => {
  const OrderItem = sequelize.define('OrderItem', {
    id: {
      type: DataTypes.BIGINT.UNSIGNED,
      primaryKey: true,
      autoIncrement: true
    },
    order_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      comment: '订单ID'
    },
    product_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      comment: '商品ID'
    },
    product_name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '商品名称'
    },
    product_image: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '商品图片'
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 1,
      comment: '数量'
    },
    price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '单价（保留字段，实际使用积分）'
    },
    total_price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '总价（保留字段，实际使用积分）'
    },
    discount_price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0,
      comment: '折扣价（保留字段，实际使用积分）'
    },
    actual_price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '实际价格'
    },
    specifications: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '规格信息'
    },
    file_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: true,
      comment: '关联的文件ID'
    },
    print_config: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '打印配置'
    },
    status: {
      type: DataTypes.TINYINT,
      allowNull: false,
      defaultValue: 0,
      comment: '状态: 0-待处理, 1-处理中, 2-已完成, 3-已取消'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '更新时间'
    }
  }, {
    tableName: 'order_items',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        name: 'idx_order_id',
        fields: ['order_id']
      },
      {
        name: 'idx_product_id',
        fields: ['product_id']
      },
      {
        name: 'idx_file_id',
        fields: ['file_id']
      }
    ]
  })

  OrderItem.associate = (models) => {
    OrderItem.belongsTo(models.Order, {
      foreignKey: 'order_id',
      as: 'order'
    })
    
    OrderItem.belongsTo(models.Product, {
      foreignKey: 'product_id',
      as: 'product'
    })
    
    OrderItem.belongsTo(models.File, {
      foreignKey: 'file_id',
      as: 'file'
    })
  }

  return OrderItem
}